package mynet;
// defualt

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Client  {
		static	JFrame ClientFrame = new JFrame("Client");
		private JTextField jtf = new JTextField();
		static  private JTextArea jta = new JTextArea();
		static JPanel p;
		static	 JScrollPane scrollP;	static String name="Anonymous";
		static int retry=0;
		static DataOutputStream toServer;
		static DataInputStream fromServer;
		static String message="";
		static	Socket kkSocket = null;
		static PrintWriter out = null;
		static BufferedReader in = null;
        static boolean connect=true;
		static int x=0;
		static	DatagramPacket packet;
		static  byte[] buf = new byte[256];
		static int listen=0;
        static MulticastSocket MCsocket;
        static InetAddress address;
        static Socket socket;
  
      	
    public  Client(){
    	p = new JPanel();
 		p.setLayout(new BorderLayout());
 		ClientFrame.setLayout(new BorderLayout());
 		p.add(new JLabel("Enter message: "), BorderLayout.WEST);
 		p.add(jtf, BorderLayout.CENTER);
 		jtf.setHorizontalAlignment(JTextField.RIGHT);
 		jtf.addActionListener(new TextFieldListener());
 		ClientFrame.add(p, BorderLayout.NORTH);
 		scrollP = new JScrollPane(jta);
 		ClientFrame.add(scrollP, BorderLayout.CENTER);
    	ClientFrame.setSize(500, 300);
 		ClientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 		ClientFrame.setVisible(true);
 		message = JOptionPane.showInputDialog(ClientFrame,"Enter your name.","Anonymous");
 		Connect();
      }  
		
    public  static void Connect(){
    	
    	String address = JOptionPane.showInputDialog(ClientFrame,"Enter Server's IP Address.", "192.168.12.1");
    	System.out.println("address: "+address);
    	
    		if(address==(null)){
    			System.exit(0);
    		}
    		try {
		@SuppressWarnings("resource")
		Socket socket = new Socket(address, 4448);
    	out = new PrintWriter(socket.getOutputStream(), true);
    	in = new BufferedReader(new InputStreamReader
 							(socket.getInputStream()));
 										
    	}
		catch (Exception e){
					
			System.out.println("er 68: "+e);
			retry++;
			
			if(retry>=3){
				System.out.println("System exit 3");
				System.exit(1);
			}
			Connect();	
			
		}
	//	sendToMCServer();
    }	
    public static void main(String[] args)  {   
    	ClientFrame.setLocationRelativeTo(null);
    	new Client();
    	try{
    	// out.write(message +" is conenected.");
    
    	//sendToMCServer();
    	System.out.println("listenning from server");
  			while(true){
  				receiveFromServer();
  				jta.append(message);
  			}
    	}
      	catch (Exception e){
		System.out.println("err 101 : "+e);
			retry++;
			 if(retry>=6){
			 		System.exit(0);
			 	}
			 Connect();
 			}
       	
    }
    
    private class TextFieldListener implements ActionListener {
 	public void actionPerformed(ActionEvent e) {
 		
 		try{
 		message=jtf.getText();
 		message = name + ": " + message;
 	//	message.trim();
 		if(message.equalsIgnoreCase("")){
 			return;
 		}
 	
        out.flush();
       	System.out.println("Sending to server ");
       	out.println(message);
 		jtf.setText(null);
 		}
 			catch (Exception ex){
			System.out.println("error 23 : "+ex);
				retry++;
 			}
 			jtf.setText(null);	
 		}
 	}
 	
 	
    public static void receiveFromServer() {
    		
   		try {
 	
         @SuppressWarnings("resource")
		MulticastSocket mcsocket = new MulticastSocket(4448);
       	 InetAddress address = InetAddress.getByName("230.0.0.1");
		 mcsocket.joinGroup(address);

         DatagramPacket packet;
    
            
		while(true){

	    	byte[] buf = new byte[256];
            packet = new DatagramPacket(buf, buf.length);
            mcsocket.receive(packet);

            message = new String(packet.getData(), 0, packet.getLength());
         
            }
            }
            
   			catch (Exception e){
			System.out.println("er 232 : "+e);
							retry++;
			
			if(retry>=3){
					int	recon =	 JOptionPane.showConfirmDialog(ClientFrame,"Connection reset. Reconnect?");
	 	 if(recon==0){
	 	 		System.out.println("Re-establishing connection....2");
				Connect();
	 	 	return;
	 	 }
	 	 else
	 	 	System.exit(0);
			
		}	
   		}
   	
   	}	
   
}
